import logging
import sys


class LogFilter(logging.Filter):
    """Filters (lets through) all messages with level < LEVEL"""

    def __init__(self, level):
        super().__init__()
        self.level = level

    def filter(self, record) -> bool:
        # "<" instead of "<=": since logger.setLevel is inclusive, this should
        # be exclusive
        return record.levelno < self.level


MIN_LEVEL = logging.DEBUG


def init() -> None:
    log_filter = LogFilter(logging.WARNING)

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.addFilter(log_filter)
    stdout_handler.setLevel(MIN_LEVEL)
    stdout_handler.setFormatter(logging.Formatter(
        "%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))

    stderr_handler = logging.StreamHandler(sys.stderr)
    stderr_handler.setLevel(max(MIN_LEVEL, logging.WARNING))
    stderr_handler.setFormatter(logging.Formatter(
        "%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
    # messages lower than WARNING go to stdout
    # messages >= WARNING (and >= STDOUT_LOG_LEVEL) go to stderr
    root_logger = logging.getLogger()
    root_logger.addHandler(stdout_handler)
    root_logger.addHandler(stderr_handler)
